//
//  ICChatPhotoViewController.m
//  ICome
//
//  Created by zhangrongwu on 16/4/27.
//  Copyright © 2016年 iCom. All rights reserved.
//  头像处理

#import "ICChatPhotoViewController.h"
#import "ICImageCropperViewController.h"
#import "UIImage+Extension.h"
#import "YYPhotoGroupView.h"
#import "UIImage+AvatarGeneration.h"

#define imageViewHeight  (App_Frame_Width - 80)

@interface ICChatPhotoViewController ()<ICImageCropperDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIScrollViewDelegate>
@property (nonatomic, strong)UIImageView *imageView;
@property (nonatomic, strong)UIImagePickerController *imagePicker;

@property (nonatomic, strong)UIButton *cameraButton;
@property (nonatomic, strong)UIButton *libraryButton;

@property (nonatomic, strong)UIButton *saveButton;
@property (nonatomic, strong)UIButton *cancelButton;
@property (nonatomic, strong)UIScrollView *scrollView;

@property (nonatomic, strong)ICGroup *group;
@property (nonatomic, assign)BOOL isMaster; // 是否为群主
@property (nonatomic, assign)BOOL isGroupHeadImage;

@end

@implementation ICChatPhotoViewController
+(ICChatPhotoViewController *)editorHeadImageGroupHeadimage:(BOOL)isGroupHeadImage Group:(ICGroup *)group isMaster:(BOOL)master {
    ICChatPhotoViewController *vc = [[ICChatPhotoViewController alloc] init];
    vc.group = group;
    vc.isMaster = master;
    vc.isGroupHeadImage = isGroupHeadImage;
    return vc;
}

#pragma mark - life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self setNav];
    
    
    if(self.isGroupHeadImage)
    {//群
         NSString *URL = [ICTools getOglImageURL:(self.group.photoId)];
        [UIImage GroupHeadView:self.imageView withUrlStr:URL withgId:self.group.gId withSize:CGSizeMake(imageViewHeight, imageViewHeight)];
//        [UIImage  GroupHeadGenerator:URL with:self.group.gId withSize:CGSizeMake(100, 100)];
//        [self.imageView sd_setImageWithURL:[NSURL URLWithString:OGLIMAGEURL(self.group.photoId)] placeholderImage:[UIImage imageNamed:@"App_group_headimg"]];
    }else{
    //个人
        NSString *URL = [ICTools getOglImageURL:([ICUser currentUser].photoId)];
        [UIImage addAvatariamgeView:self.imageView withUrlStr:URL witheId:[ICUser currentUser].eId withName:[ICUser currentUser].eName];
    }
    
//    NSString *photoId = self.isGroupHeadImage ? self.group.photoId : [ICUser currentUser].photoId;
//    UIImage *groupHeadImg = [UIImage imageNamed:@"App_group_headimg"];
//    UIImage *myHeadImg = [UIImage imageNamed:@"App_personal_headimg"];
//    UIImage *headImg = self.isGroupHeadImage ? groupHeadImg : myHeadImg;
//    
//    [self.imageView sd_setImageWithURL:[NSURL URLWithString:OGLIMAGEURL(photoId)] placeholderImage:headImg];
    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
//        [self cancelBtnClicked];
//    }];
//    [self.view addGestureRecognizer:tap];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
        UIView *fromView = nil;
        NSMutableArray *items = [[NSMutableArray alloc] init];
        YYPhotoGroupItem *item = [YYPhotoGroupItem new];
        item.thumbView = self.imageView;
        NSString *photoId = self.isGroupHeadImage ? self.group.photoId : [ICUser currentUser].photoId;
        NSString *URL = [ICTools getOglImageURL:(photoId)];
        item.largeImageURL = [NSURL URLWithString:URL];
        [items addObject:item];
        fromView = self.imageView;
        YYPhotoGroupView *v = [[YYPhotoGroupView alloc] initWithGroupItems:items];
        [v presentFromImageView:fromView toContainer:self.navigationController.view fromViewC:self animated:YES completion:nil];
    }];
    [self.imageView addGestureRecognizer:tap];

}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //self.navigationController.navigationBarHidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //self.navigationController.navigationBarHidden = NO;
}

#pragma mark - CustomDelegate
#pragma UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        return;
    } else {
        [picker dismissViewControllerAnimated:YES completion:^() {
            UIImage *portraitImg = info[UIImagePickerControllerOriginalImage];
            portraitImg = [UIImage imageByScalingToMaxSize:portraitImg];
            ICImageCropperViewController *imgEditorVC = [[ICImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, (APP_Frame_Height - App_Frame_Width) * 0.5, App_Frame_Width, App_Frame_Width) limitScaleRatio:[UIScreen mainScreen].scale];
            imgEditorVC.ratioBool = YES;
            imgEditorVC.delegate = self;
            imgEditorVC.view.backgroundColor = [UIColor blackColor];
            [self presentViewController:imgEditorVC animated:YES completion:nil];
        }];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imageCropper:(ICImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    [cropperViewController dismissViewControllerAnimated:YES completion:nil];
    [self uploadHeadImage:editedImage isGroup:YES];
}

- (void)imageCropperDidCancel:(ICImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - event response
- (void)cameraBtnClicked {
    __weak typeof(self)weak_self = self;
    [ICSystemTool checkCameraAuthorizationStatus:^{
        [weak_self imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypeCamera];
    }];
    
}

- (void)libraryBtnClicked {
    __weak typeof(self)weak_self = self;
    [ICSystemTool checkPhotoAuthorizationStatus:^{
       [weak_self imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    }];
}

- (void)saveBtnClicked {
    
    __weak typeof(self)weak_self = self;
    [ICSystemTool checkPhotoAuthorizationStatus:^{
        UIImageWriteToSavedPhotosAlbum(weak_self.imageView.image, weak_self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }];
}

- (void)cancelBtnClicked {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (error) {
        [MBProgressHUD showError:@"保存图片失败" toView:self.view];
    } else {
        [MBProgressHUD showSuccess:@"保存图片成功" toView:self.view];
    }
}

#pragma mark - private methods
// 设置页面布局
- (void)setUI {
    CGFloat margin = 15;
    [self.scrollView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    [self.imageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.scrollView.mas_top).offset(34);
        make.width.mas_equalTo(imageViewHeight);
        make.height.mas_equalTo(imageViewHeight);
    }];
    
    CGFloat btnHeight = 45 * Level;
    [self.cameraButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.imageView.mas_bottom).offset(35);
        if (self.isMaster) {
            make.height.mas_equalTo(btnHeight);
            self.cameraButton.hidden = NO;
        } else {
            make.height.mas_equalTo(0);
            self.cameraButton.hidden = YES;
        }
        make.left.equalTo(self.view.mas_left).offset(margin);
        make.right.equalTo(self.view.mas_right).offset(-margin);
    }];
    
    [self.libraryButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.cameraButton.mas_bottom).offset(15);
        if (self.isMaster) {
            make.height.mas_equalTo(btnHeight);
            self.libraryButton.hidden = NO;
        } else {
            make.height.mas_equalTo(0);
            self.libraryButton.hidden = YES;
        }
        make.left.equalTo(self.view.mas_left).offset(margin);
        make.right.equalTo(self.view.mas_right).offset(-margin);
    }];
    
    [self.saveButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.libraryButton.mas_bottom).offset(15);
        make.height.mas_equalTo(btnHeight);
        make.left.equalTo(self.view.mas_left).offset(margin);
        make.right.equalTo(self.view.mas_right).offset(-margin);
    }];
    
    [self.cancelButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.saveButton.mas_bottom).offset(15);
        make.height.mas_equalTo(btnHeight);
        make.left.equalTo(self.view.mas_left).offset(margin);
        make.right.equalTo(self.view.mas_right).offset(-margin);
        make.bottom.equalTo(self.scrollView.mas_bottom).offset(-btnHeight);
    }];
}
// 设置navigation
- (void)setNav {
    //[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    if(self.group == nil)
    {
        self.title = @"个人头像";

    }else{
        self.title = @"群头像";
    }
}

//- (UIStatusBarStyle)preferredStatusBarStyle {
//    return UIStatusBarStyleLightContent;
//}

#pragma mark - CustomDelegate

- (void)imagePickerControllerWithSourceType:(UIImagePickerControllerSourceType)sourceType {
    self.imagePicker.sourceType = sourceType;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

- (void)uploadHeadImage:(UIImage *)image isGroup:(BOOL)isGroup {
    [MBProgressHUD showMessage:@"处理中..." toView:self.view];
    NSString *filePath = @"userHeadImage";
    NSString *imgName = [[[filePath lastPathComponent] stringByDeletingPathExtension] stringByAppendingPathExtension:@"jpeg"];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.75);
    
    NSString *ownerId = self.isGroupHeadImage ? self.group.gId : [ICUser currentUser].eId;
    NSDictionary *param = @{@"ownerId":ownerId,
                            @"fileName":imgName};
    WEAKSELF
    if (self.isGroupHeadImage) { // 群组
        
        [[ICNetworkManager sharedInstance] updateGroupImage:imageData param:param success:^(id object) {
            NSString *photoId = [object objectForKey:@"data"]; // photoId
            weakSelf.imageView.image = image;
            NSString *gName = weakSelf.group.gName;
            NSString *gId   = weakSelf.group.gId;
            [ICMessageDatabase updateGroupSyn:gId gName:gName photoId:photoId];
            
            [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
            [MBProgressHUD showError:error.domain];
        }];
    } else {
        
        [[ICNetworkManager sharedInstance] updateEmpImage:imageData param:param success:^(id object) {
                NSString *photoId = [object objectForKey:@"data"]; // photoId
                weakSelf.imageView.image = image;
                [ICUser currentUser].photoId = photoId;
                [ICUser updateUserInfo];
                [ICMessageDatabase updateUserPhotoId:photoId eId:[ICUser currentUser].eId];
            
            [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
            [MBProgressHUD showError:error.domain];
        }];
    }
}

- (UIImagePickerController *)imagePicker {
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
        _imagePicker.modalPresentationStyle = UIModalPresentationCustom;
        _imagePicker.view.backgroundColor = [UIColor whiteColor];
        _imagePicker.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor whiteColor]};
    }
    return _imagePicker;
}

-(UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
        _imageView.autoresizingMask = UIViewAutoresizingNone;
        _imageView.layer.masksToBounds = YES;
        _imageView.userInteractionEnabled = YES;
        _imageView.layer.cornerRadius = 5.0;//imageViewHeight / 2;
        [self.scrollView addSubview:_imageView];
    }
    return _imageView;
}

-(UIButton *)cameraButton {
    if (!_cameraButton) {
        _cameraButton = [[UIButton alloc] init];
        [_cameraButton setTitle:@"拍照" forState:UIControlStateNormal];
        _cameraButton.titleLabel.font = [UIFont systemFontOfSize:16];
        _cameraButton.layer.cornerRadius = 5;
        _cameraButton.layer.borderWidth = 0.5;
        _cameraButton.layer.borderColor = ICRGB(0x787878).CGColor;
        _cameraButton.hidden = YES;
        [_cameraButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_cameraButton addTarget:self action:@selector(cameraBtnClicked) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:_cameraButton];
    }
    return _cameraButton;
}

-(UIButton *)libraryButton {
    if (!_libraryButton) {
        _libraryButton = [[UIButton alloc] init];
        [_libraryButton setTitle:@"从手机相册选择" forState:UIControlStateNormal];
        _libraryButton.titleLabel.font = [UIFont systemFontOfSize:16];
        _libraryButton.layer.cornerRadius = 5;
        _libraryButton.layer.borderWidth = 0.5;
        _libraryButton.layer.borderColor = ICRGB(0x787878).CGColor;
        _libraryButton.hidden = YES;
        [_libraryButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_libraryButton addTarget:self action:@selector(libraryBtnClicked) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:_libraryButton];
    }
    return _libraryButton;
}
-(UIButton *)saveButton {
    if (!_saveButton) {
        _saveButton = [[UIButton alloc] init];
        [_saveButton setTitle:@"保存照片" forState:UIControlStateNormal];
        _saveButton.titleLabel.font = [UIFont systemFontOfSize:16];
        _saveButton.layer.cornerRadius = 5;
        _saveButton.layer.borderWidth = 0.5;
        _saveButton.layer.borderColor = ICRGB(0x787878).CGColor;
        [_saveButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_saveButton addTarget:self action:@selector(saveBtnClicked) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:_saveButton];
    }
    return _saveButton;
}

-(UIButton *)cancelButton {
    if (!_cancelButton) {
        _cancelButton = [[UIButton alloc] init];
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize:16];
        _cancelButton.layer.cornerRadius = 5;
        _cancelButton.layer.borderWidth = 0.5;
        _cancelButton.layer.borderColor = ICRGB(0x787878).CGColor;
        [_cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancelBtnClicked) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:_cancelButton];
    }
    return _cancelButton;
}

-(UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.contentSize = CGSizeMake(App_Frame_Width, APP_Frame_Height);
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.delegate = self;
        _scrollView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_scrollView];
    }
    return _scrollView;
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (viewController.navigationItem.leftBarButtonItem == nil && [navigationController.viewControllers count] > 1) {
        viewController.navigationItem.leftBarButtonItem =[self createBackButton:navigationController];
    }
}

-(UIBarButtonItem*)createBackButton:(UINavigationController *)navigationController
{
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamedFromiComeSDKBundle:@"App_back_blue"] style:UIBarButtonItemStylePlain target:self action:@selector(popViewController)];
    return barButtonItem;
}

-(void)popViewController
{
    [self.imagePicker popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
